package cate.game.role.pvp.championrace;

import cate.game.pvp.championrace.ChampionRaceSpecUtils;
import cate.game.pvp.championrace.data.ChampionRaceRedPacketRecord;
import cate.game.pvp.championrace.dto.ChampionRaceRedPacketRecordData;
import cate.game.pvp.championrace.data.ChampionRaceSpec;
import cate.game.role.Role;
import cate.game.role.RoleDependent;
import cate.game.role.RoleSnapshot;
import com.google.common.collect.Sets;
import easy.java.dev.note.NoteClass;
import easy.java.dev.note.NoteField;
import org.apache.commons.lang3.StringUtils;

import java.util.List;
import java.util.Objects;
import java.util.Set;

@NoteClass("冠军赛红包数据")
public class ChampionRaceRedPacket extends RoleDependent {
    @NoteField(value = "已经领取阶段")
    public Set<ChampionRaceSpec> gotSet;

    @Override
    public void initialize(Role role) {
        super.initialize(role);

        if (Objects.isNull(gotSet)) {
            gotSet = Sets.newHashSet();
        }
    }

    public ChampionRaceRedPacketRecordData handleRedPacketReq(ChampionRaceSpec spec) {
        ChampionRaceRedPacketRecordData r;
        if (!gotSet.contains(spec)) {
            r = role.getGame().pvp.championRace.getBizHandler().getRedPacket(new RoleSnapshot(role), spec);
            if (Objects.nonNull(r.data)) {
                List<ChampionRaceRedPacketRecord> rdList = r.data;
                ChampionRaceRedPacketRecord record = rdList.stream()
                        .filter(rd -> StringUtils.equalsIgnoreCase(rd.getUid(), role.getUid()))
                        .findFirst()
                        .orElse(null);
                if (Objects.nonNull(record)) {
                    gotSet.add(record.getSpec());
                }
            }
        } else {
            r = role.getGame().pvp.championRace.getBizHandler().getRoleRedPacket(spec, role.getUid());
        }
        return r;
    }

    public byte hasRedPacket(ChampionRaceSpec spec) {
        if (!ChampionRaceSpecUtils.isBetRwd(spec)) {
            return 0;
        }

        return !gotSet.contains(spec) ? (byte) 1 : (byte) 0;
    }

    public void onSeasonSwitch() {
        gotSet.clear();
    }

    /**
     * 跨服合并兼容性处理
     * <p>
     * 在玩家上线和赛季切换的时候进行检查
     */
    public void check(int season) {
        if (gotSet.isEmpty()) {
            return;
        }
        // 大于(当前赛季-1)的所有已经领取的记录需要被清理
        // 当前赛季
        gotSet.removeIf(spec -> (season - spec.getSeason()) > 1 || (spec.getSeason() > season));
    }
}
